package com.zds.leetcode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * nums = [1,2,2]
 * [[],[1],[1,2],[1,2,2],[2],[2,2]]
 */
public class q_90 {
    public static void main(String[] args) {
        q_90 q_90 = new q_90();
        List<List<Integer>> lists = q_90.subsetsWithDup(new int[]{1, 2, 2});
        System.out.println(lists);
    }

    List<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> track = new LinkedList<>();

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        // 使得相同元素相邻
        Arrays.sort(nums);
        backtrack(nums, 0);
        return res;
    }

    void backtrack(int[] nums, int start) {
        // 返回每一层节点节点
        res.add(new LinkedList<>(track));

        for (int i=start;i<nums.length;i++) {
            // 剪枝 同一层元素相同剪枝 注意数组越界问题
            if(i>start && nums[i]==nums[i-1]){
                continue;
            }
            // 做选择
            track.add(nums[i]);
            // 递归
            backtrack(nums, i+1);
            // 撤销选择
            track.removeLast();
        }
    }
}
